package ar.com.fracervellera.web.controller;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.com.fracervellera.web.command.LoginForm;

public class LoginController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger("GooglePrivateClaendarService"); 
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if(req.getSession().getAttribute("user") != null) {
			resp.sendRedirect("/fraguion/createProject");
		}else{
			req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);	
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		if(req.getSession().getAttribute("user") != null) {
			resp.sendRedirect("/fraguion/createProject");
		}
			
		String user = req.getParameter("username");
		String password = req.getParameter("password");
		LoginForm loginForm = new LoginForm(user, password);
		
		if(user != null && password != null && user.equals("fra") && password.equals("123")){
			req.getSession().invalidate();
			req.getSession().setAttribute("user", user);
			resp.sendRedirect("/createProject");
		}else{
		 	req.setAttribute("username", user);
		 	List<String> errorList = new LinkedList<String>();
		 	errorList.add("User and password incorrect");
			req.setAttribute("error_list",errorList);
			req.setAttribute("login_form", loginForm);
			req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
		}
		
	}

}
